document.addEventListener('touchmove', function(event) {
    event.preventDefault();
}, false);

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}

// var localVideo = document.getElementById('localVideo');
// var remoteVideo = document.getElementById('remoteVideo');
var leaveVideo = document.getElementById('video-leave');
// var saveRecord = document.getElementById('record-save');
// var pauseAndGoonRecord = document.getElementById('record-pause');
// var recordRemote = document.getElementById('record-remote');
// var recordLocal = document.getElementById('record-local');
var switchCamera = document.getElementById('camera-switch');
var toSendMessage = document.getElementById('toSendMessage');
var toStartMenu = document.getElementById('toStartMenu');
var sendMessage = document.getElementById('sendMessage');

var localStream;
var remoteStream;

var connection = new RTCMultiConnection();
connection.socketURL = 'https://www.sheepony.win:443/';
// connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
connection.socketMessageEvent = 'video-conference-demo';

// setting type of media connection
connection.session = {
    audio: true,
    video: true,
    data:  true
};
//这个声音不错
connection.sdpConstraints.mandatory = {
    OfferToReceiveAudio: true,
    OfferToReceiveVideo: true,
};
connection.mediaConstraints = {
    audio: true,
    video: {
        mandatory: {
            minAspectRatio: 0.56,
            maxAspectRatio: 0.56
        },
    }
};
connection.iceServers = [];
connection.iceServers.push({
    urls: 'stun:59.110.239.23'
});
connection.iceServers.push({
    urls: 'turn:59.110.239.23:3476',
    credential: 'test',
    username: 'test'
});
var videoRoom = getUrlParam('roomName')? getUrlParam('roomName'):"testRoom";
var date = new Date();
var method;

connection.openOrJoin(videoRoom);
// if(method == 'join'){
//     console.log("join",videoRoom+date.getTime());
//     connection.join(videoRoom);
// }else {
//     console.log("open",videoRoom+date.getTime());
//     connection.open(videoRoom);
// }

connection.onstream = function(e){
    console.log("onstream",e);
    if(e.type == 'local'){
        switchCamera.disabled = false;
        leaveVideo.disabled = false;
        localStream = e.stream;
        attachMediaStream(localVideo,localStream);
        localVideo.muted = true;
    }else if(e.type == 'remote'){
        remoteStream = e.stream;
        attachMediaStream(remoteVideo,remoteStream);
        remoteVideo.muted = true;
    }
};
var chatPosition = 25;
mui('.mui-scroll-wrapper').scroll({
    scrollY: true, //是否竖向滚动
    scrollX: false, //是否横向滚动
    indicators: false, //是否显示滚动条
    bounce: true, //是否启用回弹
    deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
});
connection.onmessage = function(event) {
    console.log(event.data);
    if(event.data[0] == "switch"){
        window.location.href="video.html?videoRoom="+videoRoom;
    }else if(event.data[0] == "message"){
        showMessage(event.data[1]);
    }
}
function showMessage(message) {
    console.log(message);
    var newMesNode=document.createElement("div");
    newMesNode.innerHTML = message;
    newMesNode.setAttribute('class','chatRemote');
    newMesNode.style.bottom = chatPosition+'%';
    chatPosition +=25;
    document.getElementById('chatDisplay').appendChild(newMesNode);
}
function attachMediaStream(element, stream) {
    element.src = URL.createObjectURL(stream);
};
function reattachMediaStream(to, from) {
    var src = to.src;
    to.src = from.src;
    from.src = src;

};
localVideo.onclick = function () {
    console.log("touch localvideo");
    reattachMediaStream(localVideo,remoteVideo);
}
connection.onstreamended = function(event) {
    console.log("onstreamended",event);
};
var recordRTC;
leaveVideo.onclick = function leaveVideo() {
    console.log("leave");
    if(connection && connection.attachStreams) {
        try {
            connection.attachStreams.forEach(function(stream) {
                if(stream.id = localStream.id){
                    stream.stop();
                }
            });
            connection.close();
            connection.closeSocket();
        }
        catch(e){}
        connection = null;
    }
    window.location.href="selectPersion.html?thisPersion="+thisPersion;
}
// saveRecord.onclick = function () {
//     stop();
//     this.disabled = true;
//     pauseAndGoonRecord.disabled  = true;
//     console.log("stop-record");
//     saveRecord.disabled  = false;
//     leaveVideo.disabled = false;
//     recordRTC.stopRecording();
//     this.disabled = true;
//     if(remoteStream){
//         recordRemote.disabled = false;
//     }
//     recordLocal.disabled = false;
//     console.log("save");
//     createAndWriteFile();
// };

var loopi;
var tags;
// recordRemote.onclick = function () {
//     loopi = 0;
//     tags = 0;
//     loopfunc();
//     this.disabled = true;
//     recordLocal.disabled = true;
//     leaveVideo.disabled = true;
//     saveRecord.disabled = false;
//     pauseAndGoonRecord.disabled  = false;
//     successCallback(remoteStream);
// };
// recordLocal.onclick = function () {
//     loopi = 0;
//     tags = 0;
//     loopfunc();
//     this.disabled = true;
//     leaveVideo.disabled = true;
//     pauseAndGoonRecord.disabled  = false;
//     saveRecord.disabled = false;
//     // var mediaConstraints = {video:true,audio:true};
//     // navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
//     successCallback(localStream);
// };
// resumeRecord.onclick = function () {
//
// };

// pauseAndGoonRecord.onclick = function () {
//     if(this.innerHTML == "暂停录制"){
//         console.log("pause");
//         recordRTC.pauseRecording();
//         this.innerHTML = "继续录制"
//         pause();
//     }else {
//         this.innerHTML == "继续录制"
//         goon();
//         console.log("resume");
//         recordRTC.resumeRecording();
//         this.innerHTML = "暂停录制"
//     }
// }
var isCameraSwitch = false;
// toSendMessage.onclick = function (e) {
//     console.log("toSendMessage");
//     var btnArray = ['取消', '确定'];
//     mui.prompt('请输入消息内容:','','', btnArray, function(e) {
//         if (e.index == 1) {
//             connection.send(['message',e.value]);
//             return;
//         } else {
//             return;
//         }
//     });
// }
var moveflag = true;
toSendMessage.onclick = function () {
    if(moveflag){
        var position = -50;
        var int=self.setInterval(move,1);
        function move() {
            document.getElementById('chat').style.top = position++ + '%';
            if(position == 0){
                window.clearInterval(int);
            }
        }
    }else {
        var position = -1;
        var int=self.setInterval(move1,2);
        function move1() {
            document.getElementById('chat').style.top = position-- + '%';
            if(position == -50){
                window.clearInterval(int);
            }
        }
    }
    moveflag = !moveflag;

}


var startMenuFlag = true;
sendMessage.onclick = function () {
    if(!document.getElementById('chatContent').value){
        alert("不能发送空消息！");
    }
    var message = document.getElementById('chatContent').value;
    connection.send(['message',message]);
    var newMesNode=document.createElement("div");
    newMesNode.innerHTML = message;
    newMesNode.setAttribute('class','chatLocal');
    document.getElementById('chatDisplay').appendChild(newMesNode);
    newMesNode.style.bottom = chatPosition+'%';
    chatPosition +=25;
    document.getElementById('chatContent').value='';
}
toStartMenu.onclick = function () {
    if(startMenuFlag){
        var position = -17;
        var int=self.setInterval(move,2);
        function move() {
            document.getElementById('menu').style.bottom = position++ + '%';
            if(position ==0){
                window.clearInterval(int);
            }
        }
    }else {
        var position = -1;
        var int=self.setInterval(move,2);
        function move() {
            document.getElementById('menu').style.bottom = position-- + '%';
            if(position == -18){
                window.clearInterval(int);
            }
        }
    }
   startMenuFlag = !startMenuFlag;
}

switchCamera.onclick = function () {
    console.log("switch camera");
    var switchRoom = Math.random().toString(36).substr(2);
    console.log("switchRoom"+switchRoom);
    connection.attachStreams.forEach(function(localStream) {
        localStream.stop();
    });

    if(isCameraSwitch){
        var deviceVideoId =  connection.DetectRTC.videoInputDevices[0].id;
        isCameraSwitch = !isCameraSwitch;
    }else {
        var deviceVideoId =  connection.DetectRTC.videoInputDevices[1].id;
        isCameraSwitch = !isCameraSwitch;
    }

    var cameraOptions = {
        audio: true,
        video: {
            sourceId: deviceVideoId
        }
    };
    connection.send(["switch",switchRoom]);
    connection.leave();
    connection.open(switchRoom);
    connection.captureUserMedia(function(camera) {
        localVideo.src = URL.createObjectURL(camera);
        newStreamId = camera.id;
        var streamEvent = {
            type: 'local',
            stream: camera,
            streamid: camera.id,
            mediaElement: localVideo
        };
        connection.onstream(streamEvent);
    }, cameraOptions);

}

function errorCallback(error) {
    console.log("record error");
}
function successCallback(stream) {

    var options = {
        mimeType: 'video/webm', // or video/webm\;codecs=h264 or video/webm\;codecs=vp9
        audioBitsPerSecond: 50000,
        videoBitsPerSecond: 512000,
        // bitsPerSecond: 128000 // if this line is provided, skip above two
    };
    recordRTC = RecordRTC(stream, options);
    recordRTC.startRecording();
}

function getFileName() {
    var d = new Date();
    var time = d.getTime();
    return 'SCR'+'s'+loopi+'s'+time;
}

function createAndWriteFile() {
    var type = LocalFileSystem.PERSISTENT;
    var size = 0;
    window.requestFileSystem(type, size, successCallback, errorCallback);
    function successCallback(fs) {
        var videoDataObj = recordRTC.getBlob();
        var fileName = getFileName()+".webm";
        fs.root.getDirectory('shepCheckVideo',{create: true},function (scv) {
            scv.getFile(fileName, {create: true, exclusive: true}, function(fileEntry) {
                alert('创建文件成功');
                fileEntry.createWriter(function(fileWriter) {
                    fileWriter.onwriteend = function(e) {
                        alert('写入文件成功');
                    };
                    fileWriter.onerror = function(e) {
                        alert('Write failed: ' + e.toString());
                    };
                    fileWriter.write(videoDataObj);
                }, errorCallback);
            }, errorCallback);
        });

        // fs.root.getFile(fileName, {create: true, exclusive: true}, function(fileEntry) {
        //   alert('创建文件成功');
        //   fileEntry.createWriter(function(fileWriter) {
        //     fileWriter.onwriteend = function(e) {
        //       alert('写入文件成功');
        //     };
        //     fileWriter.onerror = function(e) {
        //       alert('Write failed: ' + e.toString());
        //     };
        //     fileWriter.write(videoDataObj);
        //   }, errorCallback);
        // }, errorCallback);
    }
    function errorCallback(error) {
        alert("ERROR: " + error.code)
    }
}
//timer


function loopfunc(){
    loopi+=1;
    if(tags==1){
        return;
    }else if(tags == 2){
        return;
    }
    setTimeout("loopfunc()",1000);
    document.getElementById("record-timer").innerHTML = loopi;
}
function pause()
{
    tags = 1;
}
function goon()
{
    tags = 0;
    setTimeout("loopfunc()",1000);
}
function stop() {
    tags = 2;
}


function leaveVideoBack() {
    console.log("leave");
    if(connection && connection.attachStreams) {
        try {
            connection.attachStreams.forEach(function(stream) {
                if(stream.id = localStream.id){
                    stream.stop();
                }
            });
            connection.close();
            connection.closeSocket();
        }
        catch(e){}
        connection = null;
    }
    window.location.href="index.html";
}

document.addEventListener("backbutton", leaveVideoBack, false);